#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QTextStream>
#include <QFile>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , edit(new QTextEdit(this))
{
    ui->setupUi(this);

    // 设置标题
    this->setWindowTitle("我的记事本");

    // 创建菜单栏
    QMenuBar* menuBar = this->menuBar();

    // 创建文件菜单
    QMenu* fileMenu = menuBar->addMenu("&文件");

    // 创建保存和加载菜单项，并添加快捷键
    QAction* saveAction = new QAction("&保存", this);
    saveAction->setShortcut(QKeySequence::Save);
    QAction* loadAction = new QAction("&加载", this);
    loadAction->setShortcut(QKeySequence::Open);

    // 添加菜单项到文件菜单
    fileMenu->addAction(saveAction);
    fileMenu->addAction(loadAction);

    // 创建中央控件
    this->setCentralWidget(edit);
    edit->setPlaceholderText("此处编写文本内容...");

    // 连接信号与槽,点击 action 时触发一定的效果
    connect(saveAction, &QAction::triggered, this, &MainWindow::save);
    connect(loadAction, &QAction::triggered, this, &MainWindow::load);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::save()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("保存文件"), "", tr("文本文件 (*.txt);;所有文件 (*)"));
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << edit->toPlainText();
            file.close();
            qDebug() << "文件已保存至: " << fileName;
        } else {
            QMessageBox::warning(this, tr("保存文件"), tr("无法保存文件 %1:\n%2.").arg(fileName).arg(file.errorString()));
        }
    }
}

void MainWindow::load()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("加载文件"), "", tr("文本文件 (*.txt);;所有文件 (*)"));
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            edit->setPlainText(in.readAll());
            file.close();
            qDebug() << "文件已加载自: " << fileName;
        } else {
            QMessageBox::warning(this, tr("加载文件"), tr("无法加载文件 %1:\n%2.").arg(fileName).arg(file.errorString()));
        }
    }
}
